package com.irdstudio.efp.flow.api.rest;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.irdstudio.basic.framework.core.constant.ApplicationConstance;
import com.irdstudio.basic.framework.core.constant.ResponseData;
import com.irdstudio.basic.framework.core.util.TimeUtil;
import com.irdstudio.basic.framework.core.vo.EngineHttpRequestVO;
import com.irdstudio.basic.framework.web.util.HttpClientUtil;
import com.irdstudio.basic.sequence.service.facade.SequenceService;
import com.irdstudio.efp.console.common.ConsoleConstant;
import com.irdstudio.efp.flow.common.constance.FlowConstance;
import com.irdstudio.efp.flow.executor.util.AbstractController;
import com.irdstudio.efp.flow.service.ColltTaskFlowAppCommService;
import com.irdstudio.efp.flow.service.FlowCommonService;
import com.irdstudio.efp.flow.service.facade.BizFlowInfoService;
import com.irdstudio.efp.flow.service.facade.FlowUrlConfigService;
import com.irdstudio.efp.flow.service.vo.BizFlowInfoVO;
import com.irdstudio.efp.riskm.common.RiskColltConstant;
import com.irdstudio.efp.riskm.service.facade.ColltSmsNoticeAppService;
import com.irdstudio.efp.riskm.service.facade.ColltTaskFlowAppService;
import com.irdstudio.efp.riskm.service.facade.ColltTaskInfoService;
import com.irdstudio.efp.riskm.service.vo.ColltSmsNoticeAppVO;
import com.irdstudio.efp.riskm.service.vo.ColltTaskFlowAppVO;
import com.irdstudio.efp.riskm.service.vo.ColltTaskInfoVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;


/**
 * Controller：催收任务流转申请表
 * @author ligm
 * @date 2019-08-27
 */
@RestController
@RequestMapping("/api")
public class ColltTaskFlowAppController extends AbstractController {

	@Autowired
	@Qualifier("colltTaskFlowAppService")
	private ColltTaskFlowAppService colltTaskFlowAppService;

	@Autowired
	@Qualifier("dbSeqService")
	private SequenceService sequenceService;

	@Autowired
	@Qualifier("colltSmsNoticeAppService")
	private ColltSmsNoticeAppService colltSmsNoticeAppService;

	@Autowired
	@Qualifier("colltTaskInfoService")
	private ColltTaskInfoService colltTaskInfoService;

	@Autowired
	@Qualifier("bizFlowInfoService")
	private BizFlowInfoService bizFlowInfoService;

	@Autowired
	@Qualifier("flowUrlConfigService")
	private FlowUrlConfigService flowUrlConfigService;

	@Autowired
	private ColltTaskFlowAppCommService colltTaskFlowAppCommService;

	@Autowired
	private FlowCommonService flowCommonService;

	/**
	 * TODO: 根据任务编号查询是否存在审批中的任务<br>
	 *
	 * 0.1:wanglihua:2019/9/2 16:13: TODO: <br>
	 * @author wanglihua
	 * @params  * @param null
	 * @return
	 * @since 2019/9/2 16:13
	 * @date 2019/9/2 16:13
	 * @version 0.1
	 */
	@RequestMapping(value="/collt/task/flow/info/{colltTaskNo}", method=RequestMethod.GET)
	public @ResponseBody
	ResponseData<Integer> queryByColltTaskNo(@PathVariable("colltTaskNo") String colltTaskNo) {
		ColltTaskFlowAppVO colltTaskFlowAppVO = new ColltTaskFlowAppVO();
		colltTaskFlowAppVO.setColltTaskNo(colltTaskNo);
		List<ColltTaskFlowAppVO> queryRs = colltTaskFlowAppService.queryByColltTaskNo(colltTaskFlowAppVO);
		int outputVo = 0;
		for (ColltTaskFlowAppVO item : queryRs) {
			if (ConsoleConstant.APRV_STATUS_02.equals(item.getApproveStatus())) {
				outputVo += 1;
			}
		}
		return getResponseData(outputVo);
	}

	/**
	 * TODO: 流转任务 提交
	 * @author xiezw
	 * @params  * @param null
	 * @return
	 * @date 2019/9/3 10:21
	 * @version 0.1
	 */
	@PostMapping(value="/collt/task/flow/app/alw")
	public @ResponseBody ResponseData<Integer>  insertTaskFlowApp(@RequestBody ColltTaskFlowAppVO inColltTaskFlowAppVo) {
		int outputVo = 0;
		setUserInfoToVO(inColltTaskFlowAppVo);
		List<ColltTaskFlowAppVO> list = new ArrayList<>();
		list.add(inColltTaskFlowAppVo);
		flowCommonService.displayUserName(list,"createUser","createUserName");
		// 查询催收任务流转申请表判断是否存在审批中的流转申请信息
		ColltTaskFlowAppVO outputColltTaskFlowAppVO = null;
		List<ColltTaskFlowAppVO> queryRs = colltTaskFlowAppService.queryByColltTaskNo(inColltTaskFlowAppVo);
		if(queryRs.size()>0){
			for (ColltTaskFlowAppVO item : queryRs) {
				if (ConsoleConstant.APRV_STATUS_02.equals(item.getApproveStatus())) {
					outputVo = -2;
					return setResponseMessage(outputVo, "该催收任务存在“审批中”的流转申请，暂无法再次发起申请");
				}
			}
		}
		//  查询催收短信通知申请表判断是否存在审批中的短信通知申请信息
		ColltSmsNoticeAppVO outputColltSmsNoticeAppVO = null;
		ColltSmsNoticeAppVO inColltSmsNoticeAppVO = new ColltSmsNoticeAppVO();
		inColltSmsNoticeAppVO.setColltTaskNo(inColltTaskFlowAppVo.getColltTaskNo());
		List<ColltSmsNoticeAppVO> queryRss = colltSmsNoticeAppService.queryByColltTaskNo(inColltSmsNoticeAppVO);
		if(queryRss.size()>0){
			for (ColltSmsNoticeAppVO items : queryRss) {
				if (ConsoleConstant.APRV_STATUS_02.equals(items.getApproveStatus())) {
					outputVo = -3;
					return setResponseMessage(outputVo, "该催收任务存在“审批中”的短信通知申请，暂无法再次发起申请");
				}
			}
		}
		//  插入数据
		inColltTaskFlowAppVo.setCreateUser(inColltTaskFlowAppVo.getLoginUserId());
		inColltTaskFlowAppVo.setCreateTime(TimeUtil.getCurrentDateTime());
		inColltTaskFlowAppVo.setLastUpdateUser(inColltTaskFlowAppVo.getLoginUserId());
		inColltTaskFlowAppVo.setLastUpdateTime(TimeUtil.getCurrentDateTime());
		inColltTaskFlowAppVo.setApproveStatus(ConsoleConstant.APRV_STATUS_01);
		inColltTaskFlowAppVo.setCreateUserOrg(inColltTaskFlowAppVo.getLoginUserOrgCode());
		try {
			String colltSeq = sequenceService.getSequence("CTFA_NO","null","null");
			inColltTaskFlowAppVo.setFlowApplyNo(colltSeq);
			outputVo = colltTaskFlowAppService.insertColltTaskFlowApp(inColltTaskFlowAppVo);
		} catch (Exception e) {
			logger.error("********************************************插入数据出错，异常信息为：", e.getMessage());
			outputVo = -1;
		}
		// 发起流程
		logger.info("即将发起专项催收人工流转审批流程，信息为:" + JSON.toJSONString(inColltTaskFlowAppVo));
		// 事件ID
		String eventId = "mColltTaskFlowEnter";
		String flowId = "FW20190910000000003";

		inColltTaskFlowAppVo.setApproveStatus(ConsoleConstant.APRV_STATUS_02);
		inColltTaskFlowAppVo.setBasicColltTaskType(RiskColltConstant.STD_COLLT_WAY_02);

		BizFlowInfoVO bizFlowInfoVO = new BizFlowInfoVO();
		bizFlowInfoVO.setBizFlowType(FlowConstance.BIZ_FLOW_TYPE_10);
		bizFlowInfoVO.setBizFlowId(flowId);
		List<BizFlowInfoVO> listFlow = bizFlowInfoService.queryBizFlowInfoByFlowType(bizFlowInfoVO);
		// 获取流程ID
		logger.info("查询到的业务流程参数为："+ JSONObject.toJSONString(listFlow));
		if (Objects.nonNull(listFlow) && listFlow.size()>0) {
			bizFlowInfoVO = listFlow.get(0);
			flowId = bizFlowInfoVO.getBizFlowId();  // 得到业务流转ID
		} else {
			//提交失败 待发起
			inColltTaskFlowAppVo.setApproveStatus(ConsoleConstant.APRV_STATUS_01);
			inColltTaskFlowAppVo.setBasicColltTaskType(null);
			colltTaskFlowAppService.updateByPk(inColltTaskFlowAppVo);
			outputVo = -4;
			return setResponseMessage(outputVo, "未配置相关信息提交失败!");
		}
		EngineHttpRequestVO eVo = new EngineHttpRequestVO();
		// 业务法人机构
		eVo.setBizLagelOrgCode(this.getUserInfo().getOrgInfo().getOrgCode());
		// 业务流水号
		eVo.setE_bizSerno(inColltTaskFlowAppVo.getFlowApplyNo());
		eVo.setFlowId(flowId);
		//事件ID
		eVo.setData(inColltTaskFlowAppVo);
		eVo.setEventId(eventId);
		eVo.setG_bizSerno(inColltTaskFlowAppVo.getFlowApplyNo());
		if (!flowCommonService.dutyFlowCheck(eventId,flowId)){
			outputVo = -1;
			return setResponseMessage(outputVo, "发起审批流程失败!原因: 流程岗位已失效");
		}
		try {
			HttpClientUtil.callFlowEngine(flowUrlConfigService.getRestfulSyncStartEventUrl(), eVo, String.class);
			inColltTaskFlowAppVo.setLastUpdateUser(inColltTaskFlowAppVo.getLoginUserId());
			outputVo = colltTaskFlowAppService.updateByPk(inColltTaskFlowAppVo);

			//更新催收任务状态为"流转中"
			ColltTaskInfoVO colltTaskInfoVO = new ColltTaskInfoVO();
			colltTaskInfoVO.setColltTaskNo(inColltTaskFlowAppVo.getColltTaskNo());
			colltTaskInfoVO.setTaskSts("04");
			outputVo = colltTaskInfoService.updateByPk(colltTaskInfoVO);
		} catch (Exception e) {
			// 发起失败
			e.printStackTrace();
			logger.error("ColltTaskFlowAppVO", e.getMessage());
			outputVo = -5;
			return setResponseMessage(outputVo, "发起专项催收人工流转申请审批流程失败!原因: " + e.getMessage());
		}
		return getResponseData(outputVo);
	}

	/**
	 * TODO: 流转信息查询
	 * @author luzhaoyu
	 * @params  * @param null
	 * @return
	 * @date 2019/9/4 10:21
	 */
	@RequestMapping(value="/collt/task/flow/app/info/{colltTaskNo}", method= RequestMethod.GET)
	public @ResponseBody ResponseData<ColltTaskFlowAppVO> queryColltTaskFlowAppInfo(@PathVariable("colltTaskNo") String colltTaskNo) {
		ColltTaskFlowAppVO colltTaskFlowAppVO = new ColltTaskFlowAppVO();
		colltTaskFlowAppVO.setColltTaskNo(colltTaskNo);
		ColltTaskFlowAppVO outputVo = colltTaskFlowAppService.queryColltTaskFlowAppInfo(colltTaskFlowAppVO);
		return getResponseData(outputVo);
	}



	private ResponseData<Integer> setResponseMessage(Integer outputVo, String message) {
		ResponseData<Integer> responseData = new ResponseData<Integer>();
		responseData.setMessage(message);
		responseData.setCode(ApplicationConstance.FAILURE);
		responseData.setSuccess(true);
		return responseData;
	}

	/**
	 * TODO: 短信通知 确认
	 * @author xiezw
	 * @params  * @param null
	 * @return
	 * @date 2019/9/24 10:24
	 * @version 0.1
	 */
	@PostMapping(value="/collt/task/flow/app/sure")
	public @ResponseBody ResponseData<Integer>  insertTaskFlowAppmessage(@RequestBody ColltSmsNoticeAppVO colltSmsNoticeAppVO) {
		int outputVo = 0;
		setUserInfoToVO(colltSmsNoticeAppVO);
		//  查询催收短信通知申请表判断是否存在审批中的短信通知申请信息
		ColltSmsNoticeAppVO outputColltSmsNoticeAppVO = null;
		ColltSmsNoticeAppVO inColltSmsNoticeAppVO = new ColltSmsNoticeAppVO();
		inColltSmsNoticeAppVO.setColltTaskNo(colltSmsNoticeAppVO.getColltTaskNo());
		List<ColltSmsNoticeAppVO> queryRss = colltSmsNoticeAppService.queryByColltTaskNo(inColltSmsNoticeAppVO);
		if(queryRss.size()>0){
			for (ColltSmsNoticeAppVO items : queryRss) {
				if (ConsoleConstant.APRV_STATUS_02.equals(items.getApproveStatus())) {
					outputVo = -3;
					return setResponseMessage(outputVo, "该催收任务存在“审批中”的短信通知申请，暂无法再次发起申请");
				}
			}
		}
		// 查询催收任务流转申请表判断是否存在审批中的流转申请信息
		ColltTaskFlowAppVO colltTaskFlowAppVO = new ColltTaskFlowAppVO();
		colltTaskFlowAppVO.setColltTaskNo(colltSmsNoticeAppVO.getColltTaskNo());
		List<ColltTaskFlowAppVO> queryRs = colltTaskFlowAppService.queryByColltTaskNo(colltTaskFlowAppVO);
		if(queryRs.size()>0){
			for (ColltTaskFlowAppVO item : queryRs) {
				if (ConsoleConstant.APRV_STATUS_02.equals(item.getApproveStatus())) {
					outputVo = -2;
					return setResponseMessage(outputVo, "该催收任务存在“审批中”的流转申请，暂无法再次发起申请");
				}
			}
		}

		colltSmsNoticeAppVO.setApproveStatus(ConsoleConstant.APRV_STATUS_01);
		try {
			String smsSeq = sequenceService.getSequence("CTSMS_NO","null","null");
			colltSmsNoticeAppVO.setSmsNoticeApp(smsSeq);
			outputVo = colltSmsNoticeAppService.insertColltSmsNoticeApp(colltSmsNoticeAppVO);
		} catch (Exception e) {
			logger.error("********************************************插入数据出错，异常信息为：", e.getMessage());
			outputVo = -1;
		}
		// 发起流程
		logger.info("即将发起短信通知审批流程，信息为:" + JSON.toJSONString(colltSmsNoticeAppVO));
		// 事件ID
		String eventId = "mColltSmsEnter";
		String flowId = "FW20190924000000002";
		BizFlowInfoVO bizFlowInfoVO = new BizFlowInfoVO();
		bizFlowInfoVO.setBizFlowType(FlowConstance.BIZ_FLOW_TYPE_10);
		bizFlowInfoVO.setBizFlowId(flowId);
		List<BizFlowInfoVO> listFlow = bizFlowInfoService.queryBizFlowInfoByFlowType(bizFlowInfoVO);
		// 获取流程ID
		logger.info("查询到的业务流程参数为："+ JSONObject.toJSONString(listFlow));
		if (Objects.nonNull(listFlow) && listFlow.size()>0) {
			bizFlowInfoVO = listFlow.get(0);
			flowId = bizFlowInfoVO.getBizFlowId();  // 得到业务流转ID
		} else {
			//提交失败 待发起
			colltSmsNoticeAppVO.setApproveStatus(ConsoleConstant.APRV_STATUS_01);
			colltSmsNoticeAppService.updateByPk(colltSmsNoticeAppVO);
			outputVo = -4;
			return setResponseMessage(outputVo, "未配置相关信息提交失败!");
		}
		EngineHttpRequestVO eVo = new EngineHttpRequestVO();
		// 业务法人机构
		eVo.setBizLagelOrgCode(this.getUserInfo().getOrgInfo().getOrgCode());
		// 业务流水号
		eVo.setE_bizSerno(colltSmsNoticeAppVO.getSmsNoticeApp());
		eVo.setFlowId(flowId);
		//事件ID
		eVo.setData(colltSmsNoticeAppVO);
		eVo.setEventId(eventId);
		eVo.setG_bizSerno(colltSmsNoticeAppVO.getSmsNoticeApp());
		if (!flowCommonService.dutyFlowCheck(eventId,flowId)){
			outputVo = -1;
			return setResponseMessage(outputVo, "发起流程失败!原因: 流程岗位已失效");
		}
		try {
			HttpClientUtil.callFlowEngine(flowUrlConfigService.getRestfulSyncStartEventUrl(), eVo, String.class);
			colltSmsNoticeAppVO.setApproveStatus(ConsoleConstant.APRV_STATUS_02);
			colltTaskFlowAppVO.setLastUpdateUser(colltTaskFlowAppVO.getLoginUserId());
			outputVo = colltSmsNoticeAppService.updateByPk(colltSmsNoticeAppVO);

			//更新催收任务状态为“短信通知中”
			ColltTaskInfoVO inTaskInfoVO = new ColltTaskInfoVO();
			inTaskInfoVO.setColltTaskNo(inColltSmsNoticeAppVO.getColltTaskNo());
			ColltTaskInfoVO qq = colltTaskInfoService.queryByPk(inTaskInfoVO);
			qq.setTaskSts("05");
			outputVo = colltTaskInfoService.updateByPk(qq);
		} catch (Exception e) {
			// 发起失败
			e.printStackTrace();
			logger.error("ColltSmsNoticeAppVO", e.getMessage());
			outputVo = -5;
			return setResponseMessage(outputVo, "发起专项催收短信通知申请审批流程失败!原因: " + e.getMessage());
		}
		return getResponseData(outputVo);
	}


	@PostMapping(value="/outs/collt/task/flow/app")
	public @ResponseBody ResponseData<Integer> submitOutsColltTaskFlowApp(@RequestBody ColltTaskFlowAppVO colltTaskFlowAppVO) {
		int output = 0;
		String colltTaskNo = colltTaskFlowAppVO.getColltTaskNo();
		int delayNum = colltTaskFlowAppCommService.countDelayIng(colltTaskNo);
		if(delayNum > 0){
			String message = "催收任务编号:" + colltTaskNo + "，存在延案申请审批中，不可进行人工流转！";
			return ResponseData.create(delayNum, ApplicationConstance.FAILURE, message, false);
		}
		int flowNum = colltTaskFlowAppCommService.countFlowIng(colltTaskNo);
		if(flowNum > 0){
			String message = "催收任务编号:" + colltTaskNo + "，存在人工流转申请审批中，不可进行人工流转！";
			return ResponseData.create(flowNum, ApplicationConstance.FAILURE, message, false);
		}
		try {
			setUserInfoToVO(colltTaskFlowAppVO);
			String flowApplyNo = sequenceService.getSequence("CTFA_NO", null, null);
			colltTaskFlowAppVO.setFlowApplyNo(flowApplyNo);
			colltTaskFlowAppVO.setApproveStatus(ConsoleConstant.APRV_STATUS_01);
			colltTaskFlowAppVO.setCreateUser(colltTaskFlowAppVO.getLoginUserId());
			colltTaskFlowAppVO.setCreateTime(TimeUtil.getCurrentDateTime());
			colltTaskFlowAppVO.setLastUpdateUser(colltTaskFlowAppVO.getLoginUserId());
			colltTaskFlowAppVO.setCreateUserOrg(colltTaskFlowAppVO.getLoginUserOrgCode());
			output = colltTaskFlowAppService.insertColltTaskFlowApp(colltTaskFlowAppVO);
			if(output > 0){
				return submitColltFlowAppr(colltTaskFlowAppVO, output);
			}
		} catch (Exception e) {
			e.printStackTrace();
			output = -1;
			return ResponseData.create(output, ApplicationConstance.FAILURE, "发起人工流转申请失败，原因为:"+e.getMessage(), false);
		}
		return getResponseData(output);
	}

	private ResponseData<Integer> submitColltFlowAppr(ColltTaskFlowAppVO colltTaskFlowAppVO, int output){
		logger.info("发起委外催收人工流转申请流程开始，信息为:" + colltTaskFlowAppVO.toString());
		setUserInfoToVO(colltTaskFlowAppVO);
		/**
		 *  广银没有法人机构的概念，业务流转信息中的"业务流转标识"无法根据业务流转类型与法人机构号查询获取
		 *  【目前解决方案】创建完业务流转，生成业务流转标识号，再拷贝到代码中（这个做法，完全符合现有的以开发人员为驱动的业务流转配置工具）
		 * @date 2019/09/21
		 */
		String flowId = "FW20190921000000015";
		EngineHttpRequestVO eVo = new EngineHttpRequestVO();
		eVo.setBizLagelOrgCode(colltTaskFlowAppVO.getLoginUserOrgCode());
		eVo.setE_bizSerno(colltTaskFlowAppVO.getFlowApplyNo());
		eVo.setFlowId(flowId);
		//业务事件标识
		eVo.setEventId(FlowConstance.OUTS_TASK_FLOW_ENTER);
		eVo.setG_bizSerno(colltTaskFlowAppVO.getFlowApplyNo());
		eVo.setBizLagelOrgCode(colltTaskFlowAppVO.getLoginUserOrgCode());
		eVo.setData(colltTaskFlowAppVO);
		if (!flowCommonService.dutyFlowCheck(FlowConstance.OUTS_TASK_FLOW_ENTER,flowId)){
			output = -1;
			return setResponseMessage(output, "发起委外催收人工流转申请流程失败!原因: 流程岗位已失效");
		}
		try {
			HttpClientUtil.callFlowEngine(flowUrlConfigService.getRestfulSyncStartEventUrl(), eVo, String.class);
			colltTaskFlowAppVO.setApproveStatus(ConsoleConstant.APRV_STATUS_02);
			colltTaskFlowAppVO.setLastUpdateUser(colltTaskFlowAppVO.getLoginUserId());
			output = colltTaskFlowAppService.updateByPk(colltTaskFlowAppVO);

			//更新催收任务状态为"流转中"
			ColltTaskInfoVO colltTaskInfoVO = new ColltTaskInfoVO();
			colltTaskInfoVO.setColltTaskNo(colltTaskFlowAppVO.getColltTaskNo());
			colltTaskInfoVO.setTaskSts("05");
			output = colltTaskInfoService.updateByPk(colltTaskInfoVO);
		} catch (Exception e) {
			logger.error(e.getMessage());
			colltTaskFlowAppService.deleteByPk(colltTaskFlowAppVO);
			output = -1;
			return ResponseData.create(output, ApplicationConstance.FAILURE, "发起委外催收人工流转申请流程失败!原因: " + e.getMessage(), false);
		}
		return ResponseData.create(output, ApplicationConstance.SUCCESS, "委外催收人工流转申请发起成功！", true);
	}
}
